import express from 'express';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import dataStore from '../data/mockData.js';
import { authMiddleware } from '../middleware/auth.js';

const router = express.Router();
const JWT_SECRET = 'your-secret-key-change-in-production';

// 用户登录
router.post('/login', async (req, res) => {
  try {
    const { username, password } = req.body;
    
    // 验证输入
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }

    // 查找用户
    const user = dataStore.getUserByUsername(username);
    if (!user) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 验证密码
    const isValidPassword = await bcrypt.compare(password, user.password);
    if (!isValidPassword) {
      return res.status(401).json({
        success: false,
        message: '用户名或密码错误'
      });
    }

    // 生成JWT token
    const token = jwt.sign(
      { 
        userId: user.id, 
        username: user.username,
        role: user.role 
      },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    // 更新最后登录时间
    dataStore.updateUser(user.id, { lastLoginAt: new Date() });

    // 存储会话
    dataStore.addSession(user.id, token);

    // 返回用户信息和token
    const { password: _, ...userInfo } = user;
    res.json({
      success: true,
      message: '登录成功',
      data: {
        user: userInfo,
        token,
        expiresIn: '24h'
      }
    });

    console.log(`✅ 用户登录成功: ${username}`);
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 用户注册
router.post('/register', async (req, res) => {
  try {
    const { username, email, password, name } = req.body;
    
    // 验证输入
    if (!username || !email || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名、邮箱和密码不能为空'
      });
    }

    // 检查用户名是否已存在
    if (dataStore.getUserByUsername(username)) {
      return res.status(400).json({
        success: false,
        message: '用户名已存在'
      });
    }

    // 检查邮箱是否已存在
    if (dataStore.getUserByEmail(email)) {
      return res.status(400).json({
        success: false,
        message: '邮箱已被注册'
      });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 创建新用户
    const newUser = dataStore.addUser({
      username,
      email,
      name: name || username,
      password: hashedPassword,
      role: 'user',
      avatar: `https://avatars.githubusercontent.com/u/${Math.floor(Math.random() * 1000)}?v=4`
    });

    res.status(201).json({
      success: true,
      message: '注册成功',
      data: {
        user: newUser
      }
    });

    console.log(`✅ 用户注册成功: ${username}`);
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 用户登出
router.post('/logout', authMiddleware, (req, res) => {
  try {
    const token = req.headers.authorization?.replace('Bearer ', '');
    if (token) {
      dataStore.removeSession(token);
    }

    res.json({
      success: true,
      message: '登出成功'
    });

    console.log(`✅ 用户登出成功: ${req.user.username}`);
  } catch (error) {
    console.error('登出错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 获取当前用户信息
router.get('/me', authMiddleware, (req, res) => {
  try {
    const user = dataStore.getUserById(req.user.userId);
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    res.json({
      success: true,
      data: {
        user
      }
    });
  } catch (error) {
    console.error('获取用户信息错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 刷新token
router.post('/refresh', authMiddleware, (req, res) => {
  try {
    const user = req.user;
    
    // 生成新token
    const newToken = jwt.sign(
      { 
        userId: user.userId, 
        username: user.username,
        role: user.role 
      },
      JWT_SECRET,
      { expiresIn: '24h' }
    );

    // 更新会话
    const oldToken = req.headers.authorization?.replace('Bearer ', '');
    if (oldToken) {
      dataStore.removeSession(oldToken);
    }
    dataStore.addSession(user.userId, newToken);

    res.json({
      success: true,
      message: 'Token刷新成功',
      data: {
        token: newToken,
        expiresIn: '24h'
      }
    });
  } catch (error) {
    console.error('刷新token错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

// 修改密码
router.post('/change-password', authMiddleware, async (req, res) => {
  try {
    const { currentPassword, newPassword } = req.body;
    
    if (!currentPassword || !newPassword) {
      return res.status(400).json({
        success: false,
        message: '当前密码和新密码不能为空'
      });
    }

    // 获取用户完整信息（包含密码）
    const fullUser = dataStore.users.find(u => u.id === req.user.userId);
    if (!fullUser) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 验证当前密码
    const isValidPassword = await bcrypt.compare(currentPassword, fullUser.password);
    if (!isValidPassword) {
      return res.status(400).json({
        success: false,
        message: '当前密码错误'
      });
    }

    // 加密新密码
    const hashedNewPassword = await bcrypt.hash(newPassword, 10);
    
    // 更新密码
    dataStore.updateUser(req.user.userId, { password: hashedNewPassword });

    res.json({
      success: true,
      message: '密码修改成功'
    });

    console.log(`✅ 用户密码修改成功: ${req.user.username}`);
  } catch (error) {
    console.error('修改密码错误:', error);
    res.status(500).json({
      success: false,
      message: '服务器内部错误'
    });
  }
});

export default router;